package com.hnucm.onlinealgstudy.controller;

import com.hnucm.onlinealgstudy.pojo.Approval;
import com.hnucm.onlinealgstudy.pojo.Notice;
import com.hnucm.onlinealgstudy.pojo.User;
import com.hnucm.onlinealgstudy.service.NoticeService;
import com.hnucm.onlinealgstudy.service.UserService;
import com.hnucm.onlinealgstudy.utils.ResultOBJ;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

@RestController
@RequestMapping("/oasadapi/notice")
public class NoticeController {
    @Autowired
    NoticeService noticeService;
    @Autowired
    UserService userService;

    // 添加消息
    @PostMapping
    public ResultOBJ postNotice(@RequestBody Notice notice){
        try {
            String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
            notice.setPost_time(date);
            if(notice.getUser_id() == null){
                User user =userService.getAllUserList(notice.getUser_name(),null,null).get(0);
                notice.setUser_id(user.getId());
            }
            noticeService.postNotice(notice);
            return ResultOBJ.ADD_SUCCESS;
        } catch (Exception e) {
            return ResultOBJ.ADD_ERROR;
        }
    }

    // 根据用户名获取该用户消息
    @GetMapping
    public List<Notice> getNoticeList(@RequestParam String user_name){
        return noticeService.getNoticeList(user_name);
    }

    // 修改状态——已读
    @PostMapping(value="/changestatus")
    public ResultOBJ changeStatus(@RequestBody Approval approval){
        try {
            noticeService.changeStatus(approval);
            return ResultOBJ.UPDATE_SUCCESS;
        } catch (Exception e) {
            return ResultOBJ.UPDATE_ERROR;
        }
    }
}
